import { JsonMetadataProvider } from '@/utils/metadata3/metadata';
import { FormInstance } from 'antd/lib/form/hooks/useForm';
import { Form } from 'antd';
import React, { ReactNodeArray } from 'react';
import { getDataCell } from './utils';
import './index.less';
import { MetadataFormContext } from './interface';

interface IMetadataFormProps {
  schema?: any;
  initialValues?: any;
  getFormInstance?: (form: FormInstance) => void;
  onFinish?: (values: any) => void;
  onValuesChange?: (changedValues: any, allValues: any) => void;
}

const MetadataForm = (props: IMetadataFormProps) => {
  const [form] = Form.useForm();
  const { schema, initialValues, onFinish, getFormInstance, onValuesChange } = props;

  const [fields, setFields] = React.useState<any>();

  /**
   * 获取form的实例
   */
  React.useEffect(() => {
    if (form) {
      getFormInstance && getFormInstance(form);
    }
  }, [form]);

  React.useEffect(() => {
    const provider = new JsonMetadataProvider();
    provider.add_types(schema);
    const FormCls = provider.get_type(schema[0].id);
    const formCls = new FormCls();
    const _fields = formCls.__type__.__fields__;
    console.log('provider', formCls, _fields);
    setFields(_fields);
  }, [schema]);

  /**
   * 渲染表单
   * @param schemaRef
   * @returns
   */
  const renderForm = (schemaRef: any[]) => {
    const _schema = schemaRef[0];
    const _properties = _schema.properties;
    const _form: ReactNodeArray = [];
    for (let i = 0; i < _properties.length; i++) {
      _form.push(getDataCell(_properties[i]));
    }
    return <>{_form}</>;
  };

  return (
    <>
      <MetadataFormContext.Provider value={{ fields, form }}>
        <Form
          className="metadata-form"
          wrapperCol={{ span: 24, offset: 0 }}
          layout="horizontal"
          form={form}
          name="control-hooks"
          initialValues={initialValues}
          onFinish={onFinish}
          onValuesChange={onValuesChange}
        >
          {renderForm(schema)}
        </Form>
      </MetadataFormContext.Provider>
    </>
  );
};

export default MetadataForm;
